package com.wizinno.android.urineflow.activity;

import android.app.ActivityManager;
import android.app.KeyguardManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import cn.hutool.core.util.ArrayUtil;
import com.wizinno.android.urineflow.R;
import com.wizinno.android.urineflow.constant.CommonControl;
import com.wizinno.android.urineflow.constant.FragmentNoConstant;
import com.wizinno.android.urineflow.constant.MessageInfo;
import com.wizinno.android.urineflow.fragment.*;
import com.wizinno.android.urineflow.receiver.ScreenOffAdminReceiver;
import com.wizinno.android.urineflow.serialport.SerialPortUtil;
import com.wizinno.android.urineflow.serialport.SerialProtocol;
import com.wizinno.android.urineflow.util.BytesUtil;
import com.wizinno.android.urineflow.util.LogUtils;
import com.wizinno.android.urineflow.util.ToastUtil;

import java.util.List;

/**
 * @author LiuMei
 * @date 2020-09-08.
 */
public abstract class BaseActivity extends FragmentActivity {

    private static final String MAIN_ACTIVITY = "MainActivity";
    private static final String SETTING_BASE_ACTIVITY = "SettingBaseActivity";

    private HomeLeftFragment homeLeftFragment;
    private HomeRightFragment homeRightFragment;

    private CheckingLeftFragment checkingLeftFragment;
    private CheckingRightFragment checkingRightFragment;

    private ReportLeftFragment reportLeftFragment;
    private ReportRightFragment reportRightFragment;

    public void toHome(boolean init) {
        if (init) {
            homeLeftFragment = new HomeLeftFragment();
            homeRightFragment = new HomeRightFragment();
            switchFragment(null, homeLeftFragment, R.id.fl_content_left);
            switchFragment(null, homeRightFragment, R.id.fl_content_right);
        } else {
            switchFragment(init ? null : reportLeftFragment, homeLeftFragment, R.id.fl_content_left);
            switchFragment(init ? null : reportRightFragment, homeRightFragment, R.id.fl_content_right);
        }
    }

    public void toChecking() {
        checkingLeftFragment = new CheckingLeftFragment();
        checkingRightFragment = new CheckingRightFragment();
        switchFragment(homeLeftFragment, checkingLeftFragment, R.id.fl_content_left);
        switchFragment(homeRightFragment, checkingRightFragment, R.id.fl_content_right);
    }

    public void toReport() {
        reportLeftFragment = new ReportLeftFragment();
        reportRightFragment = new ReportRightFragment();
        switchFragment(checkingLeftFragment, reportLeftFragment, R.id.fl_content_left);
        switchFragment(checkingRightFragment, reportRightFragment, R.id.fl_content_right);
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hideNavigationBar();
        disableKeyguard();
        screenOn();
        usbHandle();
    }

    private void usbHandle() {
        //如果不是fragment activity而且是称重状态 发送停止称重指令
        CommonControl commonControl = CommonControl.INSTANCE;
        if (!isFragmentActivity() && commonControl.isWight) {
            SerialPortUtil.stopWeight();
        }
    }

    private boolean isFragmentActivity() {
        return isMainActivity() || isSettingBaseActivity();
    }

    private boolean isMainActivity() {
        String topActivityName = getTopActivityName();
        if (topActivityName.endsWith(MAIN_ACTIVITY)) {
            return true;
        } else {
            return false;
        }
    }

    private boolean isSettingBaseActivity() {
        String topActivityName = getTopActivityName();
        if (topActivityName.endsWith(SETTING_BASE_ACTIVITY)) {
            return true;
        } else {
            return false;
        }
    }

    void handleUsbData(Bundle data) {
        byte[] receiveBytes = data.getByteArray(MessageInfo.KEY_USB_DATA);
        if (ArrayUtil.isNotEmpty(receiveBytes)) {
            if (BytesUtil.startWith(receiveBytes, SerialProtocol.A1_VERSION)) {
                byte[] version = new byte[4];
                version[0] = receiveBytes[2];
                version[1] = receiveBytes[3];
                version[2] = receiveBytes[4];
                version[3] = receiveBytes[5];
                CommonControl.setA1Version(version);
            } else if (BytesUtil.startWith(receiveBytes, SerialProtocol.A2_VERSION)) {
                byte[] version = new byte[4];
                version[0] = receiveBytes[2];
                version[1] = receiveBytes[3];
                version[2] = receiveBytes[4];
                version[3] = receiveBytes[5];
                CommonControl.setA2Version(version);
            } else if (BytesUtil.startWith(receiveBytes, SerialProtocol.READ_WEIGHT)) {
                LogUtils.d("接收：重量数据");
                if (isMainActivity() && checkingLeftFragment != null) {
                    checkingLeftFragment.handleWeightData(receiveBytes);
                } else {
                    SettingBaseActivity.setWeight(receiveBytes);
                }
            } else if (BytesUtil.startWith(receiveBytes, SerialProtocol.PEOPLE_NEAR)) {
                LogUtils.d("接收：人靠近");
                if (isMainActivity()) {
                    screenOn();
                } else {
                    SettingBaseActivity.setDistanceEvent(SerialProtocol.NEAR);
                }
            } else if (BytesUtil.startWith(receiveBytes, SerialProtocol.PEOPLE_LEAVE)) {
                LogUtils.d("接收：人离开");
                if (isMainActivity()) {
                    screenOff();
                } else {
                    SettingBaseActivity.setDistanceEvent(SerialProtocol.LEAVE);
                }
            } else if (BytesUtil.startWith(receiveBytes, SerialProtocol.BUTTON_ON)) {
                LogUtils.d("接收：按钮ON");
                SettingBaseActivity.setDistanceEvent(SerialProtocol.ON);
            } else if (BytesUtil.startWith(receiveBytes, SerialProtocol.BUTTON_OFF)) {
                LogUtils.d("接收：按钮OFF");
                SettingBaseActivity.setDistanceEvent(SerialProtocol.OFF);
            } else if (BytesUtil.startWith(receiveBytes, SerialProtocol.VALVE_STATUS_READ_PREFIX) ||
                    BytesUtil.startWith(receiveBytes, SerialProtocol.VALVE_STATUS_WRITE_PREFIX)) {
                LogUtils.d("接收：阀门状态");
                SettingBaseActivity.setValveStatus(receiveBytes);
            } else if (BytesUtil.startWith(receiveBytes, SerialProtocol.READ_ADC)) {
                LogUtils.d("接收：ADC读数");
                SettingBaseActivity.setAdc(receiveBytes);
            } else if (BytesUtil.startWith(receiveBytes, SerialProtocol.READ_CHECK_0)) {
                LogUtils.d("接收：零点校准值");
                SettingBaseActivity.setCheck0(receiveBytes);
            } else if (BytesUtil.startWith(receiveBytes, SerialProtocol.READ_CHECK_500)) {
                LogUtils.d("接收：500g校准值");
                SettingBaseActivity.setCheck500(receiveBytes);
            } else if (BytesUtil.startWith(receiveBytes, SerialProtocol.DISTANCE_PEOPLE)) {
                LogUtils.d("接收：人靠近/离开事件距离设定值（单位mm）");
                SettingBaseActivity.setDistancePeople(receiveBytes);
            } else if (BytesUtil.startWith(receiveBytes, SerialProtocol.DISTANCE_PEOPLE_TIME)) {
                LogUtils.d("接收：人靠近/离开事件检测抖动时间设定值（单位ms）");
                SettingBaseActivity.setDistancePeopleTime(receiveBytes);
            } else if (BytesUtil.startWith(receiveBytes, SerialProtocol.DISTANCE_BUTTON)) {
                LogUtils.d("接收：按钮on/off事件检测距离设定值（单位mm）");
                SettingBaseActivity.setDistanceButton(receiveBytes);
            } else if (BytesUtil.startWith(receiveBytes, SerialProtocol.DISTANCE_BUTTON_TIME)) {
                LogUtils.d("接收：按钮on/off事件检测抖动时间设定值（单位ms）");
                SettingBaseActivity.setDistanceButtonTime(receiveBytes);
            } else if (BytesUtil.startWith(receiveBytes, SerialProtocol.READ_DISTANCE)) {
                SettingBaseActivity.setDistance(receiveBytes);
            } else if (BytesUtil.startWith(receiveBytes, SerialProtocol.READ_STEERING_STATUS)) {
                LogUtils.d("接收：舵机状态");
                SettingBaseActivity.setSteeringStatus(receiveBytes);
            } else if (BytesUtil.startWith(receiveBytes, SerialProtocol.READ_STEERING_ANGLE)) {
                LogUtils.d("接收：舵机当前角度");
                SettingBaseActivity.setSteeringCurrent(receiveBytes);
            }
        }
    }

    public void switchFragment(BaseFragment from, BaseFragment to, int fragmentId) {
        if (from != to) {
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            //如果不是检测页、距离设置页则发送停止称重指令
            if (to.getNo() != FragmentNoConstant.CHECKING_LEFT || to.getNo() != FragmentNoConstant.SETTING_DISTANCE) {
                SerialPortUtil.stopWeight();
            }
            //判断有没有被添加
            if (!to.isAdded()) {
                //to没有被添加,from隐藏
                if (from != null) {
                    ft.hide(from);
                }
                //添加to
                if (to != null) {
                    ft.add(fragmentId, to).commit();
                }
            } else {
                //to已经被添加,from隐藏
                if (from != null) {
                    ft.hide(from);
                }
                //显示to
                if (to != null) {
                    ft.show(to).commit();
                }
            }
        }
    }

    /**
     * 息屏
     */
    public void screenOff() {
        DevicePolicyManager policyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        ComponentName adminReceiver = new ComponentName(this, ScreenOffAdminReceiver.class);
        boolean admin = policyManager.isAdminActive(adminReceiver);
        if (admin) {
            policyManager.lockNow();
        } else {
            ToastUtil.showLong(this, "没有设备管理权限");
        }
    }

    /**
     * 亮屏
     */
    public void screenOn() {
        PowerManager mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
        PowerManager.WakeLock mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "urineflow:wakelock");
        mWakeLock.acquire();
        mWakeLock.release();
    }

    /**
     * 禁用锁屏
     */
    public void disableKeyguard() {
        KeyguardManager km = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
        KeyguardManager.KeyguardLock k1 = km.newKeyguardLock("name");
        k1.disableKeyguard();
    }

    /**
     * 获取当前运行的Activity名称
     *
     * @return
     */
    public String getTopActivityName() {
        String topActivityClassName = null;
        ActivityManager activityManager = (ActivityManager) (getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningTaskInfo> runningTaskInfo = activityManager.getRunningTasks(1);
        if (runningTaskInfo != null) {
            ComponentName f1 = runningTaskInfo.get(0).topActivity;
            topActivityClassName = f1.getShortClassName();
            LogUtils.d("numActivities:" + runningTaskInfo.get(0).numActivities);
        }
        return topActivityClassName;
    }

    public void getAndroidScreenProperty() {
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;         // 屏幕宽度（像素）
        int height = dm.heightPixels;       // 屏幕高度（像素）
        float density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
        int densityDpi = dm.densityDpi;     // 屏幕密度dpi（120 / 160 / 240）
        // 屏幕宽度算法:屏幕宽度（像素）/屏幕密度
        int screenWidth = (int) (width / density);  // 屏幕宽度(dp)
        int screenHeight = (int) (height / density);// 屏幕高度(dp)
        Log.d("h_bl", "屏幕宽度（像素）：" + width);
        Log.d("h_bl", "屏幕高度（像素）：" + height);
        Log.d("h_bl", "屏幕密度（0.75 / 1.0 / 1.5）：" + density);
        Log.d("h_bl", "屏幕密度dpi（120 / 160 / 240）：" + densityDpi);
        Log.d("h_bl", "屏幕宽度（dp）：" + screenWidth);
        Log.d("h_bl", "屏幕高度（dp）：" + screenHeight);
    }

    /**
     * 隐藏导航栏、状态栏
     */
    public void hideNavigationBar() {
        Window window;
        window = getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE | View.SYSTEM_UI_FLAG_FULLSCREEN;
        window.setAttributes(params);

        int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN;

        if (android.os.Build.VERSION.SDK_INT >= 19) {
            uiFlags |= 0x00001000;
        } else {
            uiFlags |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
        }

        getWindow().getDecorView().setSystemUiVisibility(uiFlags);
    }
}
